require "Math"
require "Player"
require "AnAL"
require "Tile"

local socket = require "socket"
local address, port = "localhost", 12345
local entity
local updaterate = 0.1
local world = {}
local localPlayer
local t

function love.load()
  love.graphics.getBackgroundColor(10, 250, 30, 0)
  love.graphics.setMode(640, 360, false, true, 0)
  localPlayer = Player.Create(100, 300)
  key = {
    ["left"] = "a",
    ["right"] = "d",
    ["attack"] = "s",
    ["jump"] = "w"
  }
  JoinServer()
end

function love.update(dt)
  SendtoServer(dt)
  SyncPlayers(dt)
  networkstuff(dt)
  localPlayer:Update(dt)
  for k in pairs(world) do
    world[k]:Update(dt)
  end
end

function love.draw()
  local info = address, " ", port
  love.graphics.print(info, 10, 10)
  localPlayer:Draw()
  for k in pairs(world) do
    world[k]:Draw()
  end
end

function JoinServer()
  udp = socket.udp()
  udp:settimeout(0)
  udp:setpeername(address, port)
  udp:send(localPlayer:FormatString('createplayer'))
  t = 0
end

function GetNewID()
  return id
end

function networkstuff(dt)
  t = t + dt
  if (t > updaterate) then
    t=t-updaterate
    udp:send(localPlayer:FormatString('update'))
  end
    
  repeat
    data, msg = udp:receive()
    if (data) then
      print(data)
      id, cmd, params = data:match("^(%I*) (%S*) (.*)")
      local posx, posy, velx, vely = params:match("(%i*) (%i*) (%f*) (%f*)")
      assert(posx, posy)
      posx, posy = tonumber(posx), tonumber(posy)
      assert(velx, vely)
      velx, vely = tonumber(velx), tonumber(vely)
      print(params)
      if (cmd == 'createplayer') then
        world[id].CreatePlayer(posx, posy)
        world[id].velocity.x, world[id].velocity.y = velx, vely
      elseif(cmd == 'update') then
        world[id].pos.x, world[id].pos.y = posx, posy
        world[id].velocity.x, world[id].velocity.y = velx, vely
      else
        print ("unrecognised command:", cmd)
      end
      --[[
      ent, cmd, parms = data:match("^(%S*) (%S*) (.*)")
      if cmd == 'at' then
        local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
        assert(x and y)
        x, y = tonumber(x), tonumber(y)
        world[ent] = {x=x, y=y}
      else
        print("unrecognised command:", cmd)
      end]]
    elseif (msg ~= 'timeout') then
      error("Network error: "..tostring(msg))
    end
  until (not data)
end

function SyncPlayers(dt)
  --
end

function SendtoServer(dt)
  --
end